package org.operator.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.operator.OperatorDb;
import org.operator.conn.conf.ConfigDbConfig;
import org.operator.jdbc.D;
import org.operator.receive.ReceiveSource;

public  class BaseOperatorDb implements OperatorDb {

	private  Connection conn;

	private String tableName;
	
	/**
	 * 数据库名称
	 */
	private String dbName;
	
	/**
	 * 构造方法
	 * 
	 * @param tableName
	 */
	public BaseOperatorDb(String tableName, String dbName) {
		this.dbName = dbName;
		try {
			conn = D.getConnection();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public BaseOperatorDb(String tableName) {
		
		Map<String, String> conf = ConfigDbConfig.getInstance("db").getDbConf();
		
		this.dbName = conf.get("dbname");
		
		this.tableName = conf.get("perfix")+tableName;
		
		try {
			conn = D.getConnection();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public List<Map<String, Object>> getAllTable() {
		// TODO Auto-generated method stub

		String tableSql = ConfigDbConfig.getInstance("system").getLoadSql().get("get_table");

		try {
			PreparedStatement  pStmt = conn.prepareStatement(tableSql);
			
			pStmt.setString(1, this.dbName);
			
			boolean result = pStmt.execute();
			
			if (result == false) {
				return null;
			}
			
			
			List<Map<String, Object>> table = ReceiveSource.getInstance(pStmt.getResultSet()).handleResultSetToMapList();
			
			pStmt.close();
			return table;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	public List<Map<String, Object>> getTableCoulum() {
		// TODO Auto-generated method stub
		
		String columSql = ConfigDbConfig.getInstance("system").getLoadSql().get("get_colum");
		
		try {
			PreparedStatement  pStmt = conn.prepareStatement(columSql);
			
			pStmt.setString(1, this.dbName);
			
			pStmt.setString(2, this.tableName);
			
			boolean result = pStmt.execute();
			
			if (result == false) {
				return null;
			}
			
			List<Map<String, Object>> obj = ReceiveSource.getInstance(pStmt.getResultSet()).handleResultSetToMapList();
			
			pStmt.close();
			return obj;
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}
}
